<?php
require_once dirname(__FILE__) . '/common.inc.php';

if (isset($_COOKIE[LANG])) {
  $language = $_COOKIE[LANG];
} else {
  $language = 'en';
}
$smarty->assign('lang', $language);

// I18N support information here
putenv("LANG=$language"); 
setlocale(LC_ALL, $language);

// Set the text domain as 'messages'
$domain = 'messages';
bindtextdomain($domain, dirname(__FILE__). '/locale'); 
bind_textdomain_codeset($domain, "utf-8");
textdomain($domain);


if (isset($_COOKIE[USER])) {
  $_SESSION[USER] = json_decode($_COOKIE[USER]);
}

$template = MiscUtils::getParam('t', 'signin');
$options = MiscUtils::getParam('opts', json_encode(array()));
$base = MiscUtils::getParam('b', 'baseblank');

$smarty->assign('p', 'module/gui/html');
$smarty->assign('u', json_encode(array()));
$smarty->assign('d', json_encode(array()));
$smarty->assign('opts', json_encode(array()));
$smarty->assign('msg', json_encode(array()));

if (isset($_SESSION[USER])) {
  if ($template == 'signin') {
    $template = 'plugins';
  }
  $smarty->assign('user', $_SESSION[USER]);
  $smarty->assign('t', "$template");
  $smarty->assign('u', json_encode($_SESSION[USER]));
  $smarty->assign('d', time());
  $smarty->assign('opts', urldecode($options));
  
  $message = array();
  $message['plugins'] = DbUtils::get(DbUtils::createPdoInst(), 'pz_plugin', NULL, NULL, NULL, NULL, NULL, NULL);
  loadPage($template, $message);
  $smarty->display("module/gui/$base.tpl");
  return;
} else {
  $smarty->assign('t', 'signin');
  $smarty->display("admin/gui/baseblank.tpl");
  return; /* SignIn Required */
}

function loadPage($template, $message) {
  /**NOT GOOD*/
  global $smarty;
  
  switch ($template) {
    case 'plugins':
      plugins($message);
      break;
    case 'plugin':
      plugin($message);
      break;
    default:
      //header('Location: http://' . DOMAIN . PATH);
      break;
  }
}


function plugins($message) {
  global $smarty;
  $menu_id = MiscUtils::getParam('m', null);
  $smarty->assign('menu_id', $menu_id);
  
  $smarty->assign('plugins', DbUtils::get(DbUtils::createPdoInst(), 'pz_plugin', NULL, NULL, NULL, NULL, NULL, NULL)->d);
}

function plugin($message) {
  global $smarty;
  
  $plugin_id = MiscUtils::getParam('i', null);
  $plugin_folder = MiscUtils::getParam('s', null);
  $menu_id = MiscUtils::getParam('m', null);
  
  $smarty->assign('plugin_id', $plugin_id);
  $smarty->assign('menu_id', $menu_id);
  
  $cond_vals = new stdClass();
  $cond_vals->c = 't.menu_id= :v1 AND t.plugin_id= :v2';
  $cond_vals->v = array(':v1' => $menu_id, ':v2' => $plugin_id);
  $smarty->assign('num_in_page', count(DbUtils::get(DbUtils::createPdoInst(), 'pz_plugin_instance', $cond_vals, NULL, NULL, NULL, NULL, NULL)->d));
  
  $text = file_get_contents("./plugins/$plugin_folder/_store/readme.txt");
  $smarty->assign('readme', $text);
}
?>